package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.BrandMapper;
import com.changgou.goods.dao.CategoryMapper;
import com.changgou.goods.dao.SkuMapper;
import com.changgou.goods.dao.SpuMapper;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/****
 * @Author:itheima
 * @Description:Spu业务层接口实现类
 *****/
@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 还原被删除的商品
     *
     * @param spuId
     */
    @Override
    public int restore(String spuId) {
        //根据id查询spu信息
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //判断是都值逻辑删除状态
        if (!"1".equals(spu.getIsDelete())) {
            throw new RuntimeException("此商品未删除,无需恢复!");
        }
        //修改属性
        spu.setIsDelete("0");
        spu.setStatus("0");//未审核
        //执行修改
        return spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 逻辑删除
     *
     * @param spuId
     */
    @Override
    public int logicDelete(String spuId) {
        //根据id获取spu信息
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //判断是都是未删除,已下架状态
        if ("1".equals(spu.getIsMarketable())) {
            throw new RuntimeException("商品已上架,请先下架商品再执行删除操作!");
        }
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已删除,请勿重复操作!");
        }
        //设置字段 isDelete 为 1
        spu.setIsDelete("1");
        //设置为未审核状态
        spu.setStatus("0");
        //执行修改
        return spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 批量下架
     *
     * @param ids
     */
    @Override
    public int pullMany(String[] ids) {
        Spu spu = new Spu();
        //下架
        spu.setIsMarketable("0");
        //批量修改
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //相当于 id in...
        criteria.andIn("id", Arrays.asList(ids));
        //未删除
        criteria.andEqualTo("isDelete", "0");
        //上架状态
        criteria.andEqualTo("isMarketable", "1");
        return spuMapper.updateByExampleSelective(spu, example);
    }

    /**
     * 批量上架
     *
     * @param ids
     */
    @Override
    public int putMany(String[] ids) {
        Spu spu = new Spu();
        //设置为上架状态
        spu.setIsMarketable("1");
        //批量修改
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(ids));
        //下架状态
        criteria.andEqualTo("isMarketable", "0");
        //审核通过
        criteria.andEqualTo("status", "1");
        //未删除
        criteria.andEqualTo("isDelete", "0");
        return spuMapper.updateByExampleSelective(spu, example);
    }

    /**
     * 商品上架
     *
     * @param spuId
     */
    @Override
    public void put(String spuId) {
        //根据id获取spu信息
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //判断是都是已审核,未删除,未上架状态
        if ("0".equals(spu.getStatus())) {
            throw new RuntimeException("商品未审核,无法上架!");
        }
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已删除,无法上架!");
        }
        if ("1".equals(spu.getIsMarketable())) {
            throw new RuntimeException("商品已上架,无需重复上架!");
        }
        //修改状态
        spu.setIsMarketable("1");
        //执行修改
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 商品下架
     *
     * @param spuId
     */
    @Override
    public void pull(String spuId) {
        //根据id获取spu信息
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //判断是都是未删除,已上架状态
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已删除,无法下架!");
        }
        if (!"1".equals(spu.getIsMarketable())) {
            throw new RuntimeException("商品未上架,无需下架!");
        }
        //修改状态
        spu.setIsMarketable("0");
        //执行修改
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 商品审核+自动上架
     *
     * @param spuId
     */
    @Override
    public void audit(String spuId) {
        //根据id获取spu信息
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //判断是都是未审核,未删除状态
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已删除,无法上架!");
        }
        if ("1".equals(spu.getStatus())) {
            throw new RuntimeException("商品已审核,请勿重复操作!");
        }
        //最后,修改状态为==>已审核,已上架
        spu.setStatus("1");
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 根据spuId查找spu和对应的sku集合
     *
     * @param spuId
     */
    @Override
    public Goods findBySpuId(String spuId) {
        //根据spuId查找spu的信息
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //根据spuId查找sku的信息
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skuList = skuMapper.select(sku);
        //封装到Goods
        Goods goods = new Goods();
        goods.setSkuList(skuList);
        goods.setSpu(spu);
        return goods;
    }

    /**
     * 添加spu+sku / 修改
     *
     * @param goods
     */
    @Override
    public void save(Goods goods) {
        //通过goods获取spu
        Spu spu = goods.getSpu();
        if (StringUtils.isEmpty(spu.getId())) {
            //没有id,代表新增
            //生成id,并绑定spu
            spu.setId("No" + idWorker.nextId());
            //添加数据库
            spuMapper.insertSelective(spu);
        } else {
            //id不为空,代表为修改
            spuMapper.updateByPrimaryKeySelective(spu);
            //获取spu的id
            String spuId = spu.getId();
            //根据spu的id删除对应的skuList,添加新的skuList
            Sku sku = new Sku();
            sku.setSpuId(spuId);
            skuMapper.delete(sku);
        }

        //获取sku
        List<Sku> skuList = goods.getSkuList();
        //获取spu的name
        String name = spu.getName();
        //创建date
        Date date = new Date();
        Integer category3Id = spu.getCategory3Id();
        //获取分类的name属性
        Category category = categoryMapper.selectByPrimaryKey(category3Id);
        String categoryName = category.getName();
        Integer brandId = spu.getBrandId();
        //获取品牌名
        Brand brand = brandMapper.selectByPrimaryKey(brandId);
        String brandName = brand.getName();
        for (Sku sku : skuList) {
            String spec = sku.getSpec();
            Map<String, String> map = JSON.parseObject(spec, Map.class);
            Set<Map.Entry<String, String>> entrySet = map.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                name += " "+entry.getValue();
            }
            sku.setName(name);
            sku.setId("No" + idWorker.nextId());
            sku.setCreateTime(date);
            sku.setUpdateTime(date);
            sku.setSpuId(spu.getId());
            sku.setBrandName(brandName);
            sku.setCategoryId(category3Id);
            sku.setCategoryName(categoryName);

            //添加sku
            skuMapper.insertSelective(sku);
        }
    }

    /**
     * Spu条件+分页查询
     * @param spu 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<Spu> findPage(Spu spu, int page, int size){
        //分页
        PageHelper.startPage(page,size);
        //搜索条件构建
        Example example = createExample(spu);
        //执行搜索
        return new PageInfo<Spu>(spuMapper.selectByExample(example));
    }

    /**
     * Spu分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Spu> findPage(int page, int size){
        //静态分页
        PageHelper.startPage(page,size);
        //分页查询
        return new PageInfo<Spu>(spuMapper.selectAll());
    }

    /**
     * Spu条件查询
     * @param spu
     * @return
     */
    @Override
    public List<Spu> findList(Spu spu){
        //构建查询条件
        Example example = createExample(spu);
        //根据构建的条件查询数据
        return spuMapper.selectByExample(example);
    }


    /**
     * Spu构建查询对象
     * @param spu
     * @return
     */
    public Example createExample(Spu spu){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(spu!=null){
            // 主键
            if(!StringUtils.isEmpty(spu.getId())){
                    criteria.andEqualTo("id",spu.getId());
            }
            // 货号
            if(!StringUtils.isEmpty(spu.getSn())){
                    criteria.andEqualTo("sn",spu.getSn());
            }
            // SPU名
            if(!StringUtils.isEmpty(spu.getName())){
                    criteria.andLike("name","%"+spu.getName()+"%");
            }
            // 副标题
            if(!StringUtils.isEmpty(spu.getCaption())){
                    criteria.andEqualTo("caption",spu.getCaption());
            }
            // 品牌ID
            if(!StringUtils.isEmpty(spu.getBrandId())){
                    criteria.andEqualTo("brandId",spu.getBrandId());
            }
            // 一级分类
            if(!StringUtils.isEmpty(spu.getCategory1Id())){
                    criteria.andEqualTo("category1Id",spu.getCategory1Id());
            }
            // 二级分类
            if(!StringUtils.isEmpty(spu.getCategory2Id())){
                    criteria.andEqualTo("category2Id",spu.getCategory2Id());
            }
            // 三级分类
            if(!StringUtils.isEmpty(spu.getCategory3Id())){
                    criteria.andEqualTo("category3Id",spu.getCategory3Id());
            }
            // 模板ID
            if(!StringUtils.isEmpty(spu.getTemplateId())){
                    criteria.andEqualTo("templateId",spu.getTemplateId());
            }
            // 运费模板id
            if(!StringUtils.isEmpty(spu.getFreightId())){
                    criteria.andEqualTo("freightId",spu.getFreightId());
            }
            // 图片
            if(!StringUtils.isEmpty(spu.getImage())){
                    criteria.andEqualTo("image",spu.getImage());
            }
            // 图片列表
            if(!StringUtils.isEmpty(spu.getImages())){
                    criteria.andEqualTo("images",spu.getImages());
            }
            // 售后服务
            if(!StringUtils.isEmpty(spu.getSaleService())){
                    criteria.andEqualTo("saleService",spu.getSaleService());
            }
            // 介绍
            if(!StringUtils.isEmpty(spu.getIntroduction())){
                    criteria.andEqualTo("introduction",spu.getIntroduction());
            }
            // 规格列表
            if(!StringUtils.isEmpty(spu.getSpecItems())){
                    criteria.andEqualTo("specItems",spu.getSpecItems());
            }
            // 参数列表
            if(!StringUtils.isEmpty(spu.getParaItems())){
                    criteria.andEqualTo("paraItems",spu.getParaItems());
            }
            // 销量
            if(!StringUtils.isEmpty(spu.getSaleNum())){
                    criteria.andEqualTo("saleNum",spu.getSaleNum());
            }
            // 评论数
            if(!StringUtils.isEmpty(spu.getCommentNum())){
                    criteria.andEqualTo("commentNum",spu.getCommentNum());
            }
            // 是否上架,0已下架，1已上架
            if(!StringUtils.isEmpty(spu.getIsMarketable())){
                    criteria.andEqualTo("isMarketable",spu.getIsMarketable());
            }
            // 是否启用规格
            if(!StringUtils.isEmpty(spu.getIsEnableSpec())){
                    criteria.andEqualTo("isEnableSpec",spu.getIsEnableSpec());
            }
            // 是否删除,0:未删除，1：已删除
            if(!StringUtils.isEmpty(spu.getIsDelete())){
                    criteria.andEqualTo("isDelete",spu.getIsDelete());
            }
            // 审核状态，0：未审核，1：已审核，2：审核不通过
            if(!StringUtils.isEmpty(spu.getStatus())){
                    criteria.andEqualTo("status",spu.getStatus());
            }
        }
        return example;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id){
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (!"1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品无法删除!");
        }
        spuMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改Spu
     * @param spu
     */
    @Override
    public void update(Spu spu){
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 增加Spu
     * @param spu
     */
    @Override
    public void add(Spu spu){
        spuMapper.insert(spu);
    }

    /**
     * 根据ID查询Spu
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id){
        return  spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询Spu全部数据
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }
}
